package clientView;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import object.Level;
import object.Role;
import object.Users;
import objectView.UserAuthorization;
import utility.StringUtil;
import clientMain.Login;
import clientMain.Main;
import clientUtilGUI.KeyValue;
import clientUtilGUI.UtilityGUI;
import database.LevelDelegate;
import database.UserDelegate;

public class User_Edit extends JScrollPane implements ActionListener{

	private JTable tblListAuth;
	private JScrollPane scrollPaneTblAuth;
	private JPanel panelEdit;
	private JLabel lblLevel;
	private JComboBox cbbLvl;
	
	private JLabel lblListAccount;
	private JLabel lblListAuthorization;
	private JLabel lblUserName;
	private JTextField txtUserName;
	private JLabel lblEmployeeId;
	private JTextField txtEmId;
	private JLabel lblRole;
	private JTextField txtRoleName;
	private JLabel lblRoleDescribe;
	private JTextField txtRoleDes;
	private JPanel panelBtn;
	private JButton btnEdit;
	private JButton btnCancel;
	private JList jListAcc;
	private JLabel lblEdit;
	private JLabel lblResult;
	
	private UserDelegate userDelegate = new UserDelegate();
	private UserAuthorization user;
	private int level;
	private String roleName;
	private String roleDes;
	private Vector<String> vAuthorizationAdd;
	private String listRMPAdd;
	private Vector<String> vIndex;
	private String listRMPDel;
	
	
	public User_Edit() {
		setViewportView(initComponet());
		setBorder(new EmptyBorder(0, 0, 0, 0));
	}
	
	private JPanel initComponet() {
		JPanel panel = new JPanel();
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{300, 0};
		gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
		gridBagLayout.columnWeights = new double[]{1.0, 0.0};
		gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 1.0};
		panel.setLayout(gridBagLayout);
		
		JLabel lblHeader = new JLabel("View And Edit Account");
		lblHeader.setFont(UtilityGUI.fontHeader1);
		lblHeader.setForeground(UtilityGUI.colorHeader1);
		GridBagConstraints gbc_lblHeader = new GridBagConstraints();
		gbc_lblHeader.gridwidth = 2;
		gbc_lblHeader.insets = new Insets(10, 10, 12, 10);
		gbc_lblHeader.gridx = 0;
		gbc_lblHeader.gridy = 0;
		panel.add(lblHeader, gbc_lblHeader);
		
		lblListAccount = new JLabel("List Account");
		lblListAccount.setFont(UtilityGUI.fontHeader2);
		lblListAccount.setForeground(UtilityGUI.colorHeader2);
		GridBagConstraints gbc_lblListAccount = new GridBagConstraints();
		gbc_lblListAccount.anchor = GridBagConstraints.WEST;
		gbc_lblListAccount.insets = new Insets(0, 10, 5, 10);
		gbc_lblListAccount.gridx = 0;
		gbc_lblListAccount.gridy = 1;
		panel.add(lblListAccount, gbc_lblListAccount);
		
		lblListAuthorization = new JLabel("List Authorization");
		lblListAuthorization.setFont(UtilityGUI.fontHeader2);
		lblListAuthorization.setForeground(UtilityGUI.colorHeader2);
		GridBagConstraints gbc_lblListAuthorization = new GridBagConstraints();
		gbc_lblListAuthorization.anchor = GridBagConstraints.WEST;
		gbc_lblListAuthorization.insets = new Insets(0, 0, 5, 10);
		gbc_lblListAuthorization.gridx = 1;
		gbc_lblListAuthorization.gridy = 1;
		panel.add(lblListAuthorization, gbc_lblListAuthorization);
		
		int lvl = Login.listAuthorization.get(0).getLvlValue();
		Vector<Users> listUser = userDelegate.getlistAcc(Main.userId, lvl);
		DefaultListModel model = new DefaultListModel();
		for(int i=0; i < listUser.size(); i++){
			String userId = Integer.toString(listUser.get(i).getUserId());
			String userName = (i+1)+". "+listUser.get(i).getUserName();
			model.add(i, new KeyValue(userId, userName));
		}
		jListAcc = new JList(model);
		int total = listUser.size();
		UtilityGUI.styleJList(jListAcc, total);
		jListAcc.setFixedCellWidth(185);
		jListAcc.setToolTipText("Click Edit");
		jListAcc.setBackground(getBackground());
		jListAcc.addMouseListener(new MouseListAcc());
		GridBagConstraints gbc_jListAcc = new GridBagConstraints();
		gbc_jListAcc.anchor = GridBagConstraints.NORTHWEST;
		gbc_jListAcc.insets = new Insets(0, 10, 5, 10);
		gbc_jListAcc.gridx = 0;
		gbc_jListAcc.gridy = 2;
		panel.add(jListAcc, gbc_jListAcc);
		
		panelEdit = edit();
		GridBagConstraints gbc_panelEdit = new GridBagConstraints();
		gbc_panelEdit.fill = GridBagConstraints.BOTH;
		gbc_panelEdit.anchor = GridBagConstraints.NORTH;
		gbc_panelEdit.insets = new Insets(5, 10, 5, 10);
		gbc_panelEdit.gridx = 0;
		gbc_panelEdit.gridy = 3;
		panel.add(panelEdit, gbc_panelEdit);
		
		scrollPaneTblAuth = new JScrollPane();		
		scrollPaneTblAuth.setPreferredSize(new Dimension(500, 450));
		GridBagConstraints gbc_scrollPaneTblAuth = new GridBagConstraints();
		gbc_scrollPaneTblAuth.gridheight = 2;
		gbc_scrollPaneTblAuth.anchor = GridBagConstraints.NORTHWEST;
		gbc_scrollPaneTblAuth.insets = new Insets(0, 0, 5, 10);
		gbc_scrollPaneTblAuth.gridx = 1;
		gbc_scrollPaneTblAuth.gridy = 2;
		panel.add(scrollPaneTblAuth, gbc_scrollPaneTblAuth);
		
		return panel;
	}			
	
	private JPanel edit(){
		JPanel panel = new JPanel();
		GridBagLayout gbl_panelEdit = new GridBagLayout();
		gbl_panelEdit.columnWidths = new int[]{0, 0, 0};
		gbl_panelEdit.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
		gbl_panelEdit.columnWeights = new double[]{0.0, 0.0, 1.0};
		gbl_panelEdit.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0};
		panel.setLayout(gbl_panelEdit);
		
		lblEdit = new JLabel("Edit Account");
		lblEdit.setFont(UtilityGUI.fontHeader2);
		lblEdit.setForeground(UtilityGUI.colorHeader2);
		GridBagConstraints gbc_lblEdit = new GridBagConstraints();
		gbc_lblEdit.anchor = GridBagConstraints.WEST;
		gbc_lblEdit.gridwidth = 2;
		gbc_lblEdit.insets = new Insets(0, 0, 5, 0);
		gbc_lblEdit.gridx = 0;
		gbc_lblEdit.gridy = 0;
		panel.add(lblEdit, gbc_lblEdit);
		
		lblUserName = new JLabel("Account :");
		lblUserName.setFont(UtilityGUI.fontHeader3);
		GridBagConstraints gbc_lblUserName = new GridBagConstraints();
		gbc_lblUserName.insets = new Insets(0, 0, 5, 5);
		gbc_lblUserName.anchor = GridBagConstraints.WEST;
		gbc_lblUserName.gridx = 0;
		gbc_lblUserName.gridy = 1;
		panel.add(lblUserName, gbc_lblUserName);
		
		txtUserName = new JTextField();
		txtUserName.setColumns(20);
		txtUserName.setEditable(false);
		GridBagConstraints gbc_txtUserName = new GridBagConstraints();
		gbc_txtUserName.fill = GridBagConstraints.BOTH;
		gbc_txtUserName.insets = new Insets(0, 0, 5, 0);
		gbc_txtUserName.gridx = 1;
		gbc_txtUserName.gridy = 1;
		panel.add(txtUserName, gbc_txtUserName);
		
		lblEmployeeId = new JLabel("Employee Id :");
		lblEmployeeId.setFont(UtilityGUI.fontHeader3);
		GridBagConstraints gbc_lblEmployeeId = new GridBagConstraints();
		gbc_lblEmployeeId.anchor = GridBagConstraints.WEST;
		gbc_lblEmployeeId.insets = new Insets(3, 0, 5, 5);
		gbc_lblEmployeeId.gridx = 0;
		gbc_lblEmployeeId.gridy = 2;
		panel.add(lblEmployeeId, gbc_lblEmployeeId);
		
		txtEmId = new JTextField();
		txtEmId.setEditable(false);
		GridBagConstraints gbc_txtEmId = new GridBagConstraints();
		gbc_txtEmId.insets = new Insets(3, 0, 5, 0);
		gbc_txtEmId.fill = GridBagConstraints.BOTH;
		gbc_txtEmId.gridx = 1;
		gbc_txtEmId.gridy = 2;
		panel.add(txtEmId, gbc_txtEmId);
		
		lblRole = new JLabel("Role :");
		lblRole.setFont(UtilityGUI.fontHeader3);
		GridBagConstraints gbc_lblRole = new GridBagConstraints();
		gbc_lblRole.anchor = GridBagConstraints.WEST;
		gbc_lblRole.insets = new Insets(3, 0, 5, 5);
		gbc_lblRole.gridx = 0;
		gbc_lblRole.gridy = 3;
		panel.add(lblRole, gbc_lblRole);
		
		txtRoleName = new JTextField();
		GridBagConstraints gbc_txtRole = new GridBagConstraints();
		gbc_txtRole.insets = new Insets(3, 0, 5, 0);
		gbc_txtRole.fill = GridBagConstraints.BOTH;
		gbc_txtRole.gridx = 1;
		gbc_txtRole.gridy = 3;
		panel.add(txtRoleName, gbc_txtRole);
		
		lblRoleDescribe = new JLabel("Role Describe :");
		lblRoleDescribe.setFont(UtilityGUI.fontHeader3);
		GridBagConstraints gbc_lblRoleDescribe = new GridBagConstraints();
		gbc_lblRoleDescribe.anchor = GridBagConstraints.WEST;
		gbc_lblRoleDescribe.insets = new Insets(3, 0, 5, 5);
		gbc_lblRoleDescribe.gridx = 0;
		gbc_lblRoleDescribe.gridy = 4;
		panel.add(lblRoleDescribe, gbc_lblRoleDescribe);
		
		txtRoleDes = new JTextField();
		GridBagConstraints gbc_txtRoleDes = new GridBagConstraints();
		gbc_txtRoleDes.insets = new Insets(3, 0, 5, 0);
		gbc_txtRoleDes.fill = GridBagConstraints.BOTH;
		gbc_txtRoleDes.gridx = 1;
		gbc_txtRoleDes.gridy = 4;
		panel.add(txtRoleDes, gbc_txtRoleDes);		
		
		if(Login.listAuthorization.get(0).getLvlValue() == 1){
			lblLevel = new JLabel("Level :");
			lblLevel.setFont(UtilityGUI.fontHeader3);
			GridBagConstraints gbc_lblLevel = new GridBagConstraints();
			gbc_lblLevel.anchor = GridBagConstraints.WEST;
			gbc_lblLevel.insets = new Insets(3, 0, 5, 5);
			gbc_lblLevel.gridx = 0;
			gbc_lblLevel.gridy = 5;
			panel.add(lblLevel, gbc_lblLevel);
			
			cbbLvl = new JComboBox();
			Vector<Level> listLvl;
			cbbLvl.setFont(UtilityGUI.fontComboBox);
			LevelDelegate lvlDelegate = new LevelDelegate();
			listLvl = lvlDelegate.getListLvl();
			cbbLvl.addItem("-- Select Level --");
			for(int i=0;i<listLvl.size();i++){
				String id = Integer.toString(listLvl.get(i).getLvlValue());
				String value = listLvl.get(i).getLvlDescribe();
				cbbLvl.addItem(new KeyValue(id, value));
			}
			GridBagConstraints gbc_comboBox = new GridBagConstraints();
			gbc_comboBox.insets = new Insets(3, 0, 5, 0);
			gbc_comboBox.fill = GridBagConstraints.BOTH;
			gbc_comboBox.gridx = 1;
			gbc_comboBox.gridy = 5;
			panel.add(cbbLvl, gbc_comboBox);
		}
		
		panelBtn = new JPanel();
		GridBagConstraints gbc_panelBtn = new GridBagConstraints();
		gbc_panelBtn.anchor = GridBagConstraints.NORTH;
		gbc_panelBtn.gridwidth = 3;
		gbc_panelBtn.insets = new Insets(3, 0, 5, 0);
		gbc_panelBtn.fill = GridBagConstraints.BOTH;
		gbc_panelBtn.gridx = 0;
		gbc_panelBtn.gridy = 6;
		panel.add(panelBtn, gbc_panelBtn);
		
		btnEdit = new JButton("Edit");
		btnEdit.setMnemonic(KeyEvent.VK_ENTER);
		btnEdit.setFont(UtilityGUI.fontBtnForm);
		btnEdit.addActionListener(this);
		panelBtn.add(btnEdit);
		
		btnCancel = new JButton("Cancel");		
		btnCancel.setFont(UtilityGUI.fontBtnForm);
		btnCancel.addActionListener(this);
		panelBtn.add(btnCancel);
		
		lblResult = new JLabel("");
		lblResult.setFont(UtilityGUI.fontLblForm);
		lblResult.setForeground(UtilityGUI.colorNote);
		GridBagConstraints gbc_lblResult = new GridBagConstraints();
		gbc_lblResult.anchor = GridBagConstraints.NORTHWEST;
		gbc_lblResult.gridwidth = 2;
		gbc_lblResult.insets = new Insets(3, 0, 5, 0);
		gbc_lblResult.gridx = 0;
		gbc_lblResult.gridy = 7;
		panel.add(lblResult, gbc_lblResult);
		return panel;
	}
	
	private class MouseListAcc extends MouseAdapter{
		public void mouseClicked(MouseEvent e) {
			if((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0){
				lblResult.setText("");
				int userId = Integer.parseInt(((KeyValue)jListAcc.getSelectedValue()).getKey());
				String uName = ((KeyValue)jListAcc.getSelectedValue()).getValue();
				uName = StringUtil.subStr(uName, ". ").get(1);
				tblListAuth = UtilityGUI.getTblAuthorization(uName);
				tblListAuth.addFocusListener(new FocusAdapter() {
					public void focusGained(FocusEvent e) {
						lblResult.setText("");
					}
				});
				scrollPaneTblAuth.setViewportView(tblListAuth);
				user = userDelegate.getAccInfo(userId); 
				txtUserName.setText(user.getUserName());
				txtEmId.setText(user.getUserInfo());
				txtRoleName.setText(user.getRoleName());
				txtRoleName.addFocusListener(new FocusListener() {
					@Override
					public void focusLost(FocusEvent e) {
						txtRoleName.setText(StringUtil.removeUnwantedSpace(txtRoleName.getText()));
						if(txtRoleName.getText().isEmpty()){
							txtRoleName.setText(user.getRoleName());
						}
					}	
					@Override
					public void focusGained(FocusEvent e) {
						lblResult.setText("");
						txtRoleName.setText("");
					}
				});
				txtRoleDes.setText(user.getRoleDes());
				txtRoleDes.addFocusListener(new FocusListener() {
					@Override
					public void focusLost(FocusEvent e) {
						if(!txtRoleDes.getText().equals(user.getRoleDes())){
							txtRoleDes.setText(user.getRoleDes());
						}						
					}
					@Override
					public void focusGained(FocusEvent e) {
						lblResult.setText("");
						txtRoleDes.setText("");						
					}
				});
				
				if(Login.listAuthorization.get(0).getLvlValue() == 1){
					int index = 0;
					for(int i = 1; i<cbbLvl.getItemCount(); i++){
					int lvlId = Integer.parseInt(((KeyValue)cbbLvl.getItemAt(i)).getKey());
						if(lvlId == user.getLvlValue()){
							index = i;
							break;
						}
					}
					cbbLvl.setSelectedIndex(index);
				}
			}
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == btnEdit){
			if(tblListAuth == null){
				return;
			}
			
			//	VALID ROLE NAME
			if(!txtRoleName.getText().equals(user.getRoleName())){
				if(!StringUtil.isValidRoleName(txtRoleName.getText())){
					JOptionPane.showMessageDialog(null, UtilityGUI.errorValidRoleName, 
							UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
					txtRoleName.requestFocusInWindow();
					return;
				}else{
					roleName = txtRoleName.getText();
					if(userDelegate.isExistsRoleName(roleName)){
						JOptionPane.showMessageDialog(null, UtilityGUI.errorExistsRoleName, 
								UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
						txtRoleName.requestFocusInWindow();
						return;
					}
				}
			}else{
				roleName = user.getRoleName();
			}
			
			//	VALID ROLE DESCRIBLE
			roleDes = txtRoleDes.getText();
			
			//	VALID AND GET LEVEL
			if(Login.listAuthorization.get(0).getLvlValue()==1){
				if(cbbLvl.getSelectedIndex() == 0){
					cbbLvl.requestFocusInWindow();
					return;
				}else{
					level = Integer.parseInt(((KeyValue)cbbLvl.getSelectedItem()).getKey());
				}
			}else{
				level = user.getLvlValue();
			}
			
			// LIST RMP
			boolean flag = false;
			for(int i=0; i<Login.listAuthorization.size(); i++){
				if((Boolean) tblListAuth.getValueAt(i, 4) == true){
					flag = true;
					break;
				}
			}
			if(flag == false){
				JOptionPane.showMessageDialog(null, UtilityGUI.errorPickAuthorization, 
						UtilityGUI.titleAlert, JOptionPane.ERROR_MESSAGE);
				return;
			}
			Vector<UserAuthorization> listAuthOld = userDelegate.getListAuthorizations(user.getUserName());
			Vector<String> vAuthOld = new Vector<String>();
			for(int i=0; i<listAuthOld.size(); i++){
				vAuthOld.add(listAuthOld.get(i).getModuleId()+"."+listAuthOld.get(i).getPermId());
			}
			vAuthorizationAdd = new Vector<String>();
			vIndex = new Vector<String>();
			listRMPAdd = "";
			listRMPDel = "";
			for(int i=0; i<Login.listAuthorization.size(); i++){
				if((Boolean) tblListAuth.getValueAt(i, 4) == true){
					String moduleId = ((KeyValue)tblListAuth.getValueAt(i, 1)).getKey();
					String permId = ((KeyValue)tblListAuth.getValueAt(i, 3)).getKey();
					vAuthorizationAdd.add(moduleId +"."+ permId);
				}
			}
			for(int i=0; i<vAuthorizationAdd.size(); i++){
				for(int j=0; j<vAuthOld.size(); j++){
					if(vAuthorizationAdd.get(i).equals(vAuthOld.get(j))){
						vIndex.add(vAuthorizationAdd.get(i));
					}
				}
			}
			for(int i=0; i<vIndex.size(); i++){
				vAuthorizationAdd.remove(vIndex.get(i));
				vAuthOld.remove(vIndex.get(i));
			}
			for(int i=0; i<vAuthorizationAdd.size(); i++){
				if(i == vAuthorizationAdd.size()-1){
					listRMPAdd += vAuthorizationAdd.get(i);
				}else
					listRMPAdd += vAuthorizationAdd.get(i)+",";
			}
			for(int i=0; i<vAuthOld.size();i++){
				if(i == vAuthOld.size()-1){
					listRMPDel += vAuthOld.get(i);
				}else
					listRMPDel += vAuthOld.get(i)+",";
			}
			
			if(roleName.equals(user.getRoleName()) && roleDes.equals(user.getRoleDes()) &&
					level == user.getLvlValue() && listRMPAdd.isEmpty() && listRMPDel.isEmpty()){
				return;
			}
			Users updateUser = new Users();
			updateUser.setUserName(user.getUserName());
			updateUser.setLvlValue(level);
			Role role = new Role();
			role.setRoleId(user.getRoleId());
			role.setRoleName(roleName);
			role.setRoleDescribe(roleDes);
			
			boolean flag1 = userDelegate.editAcc(updateUser, role, listRMPAdd, listRMPDel);
			if(flag1){
				lblResult.setText("Edit Successfully !");
			}else{
				JOptionPane.showMessageDialog(null, UtilityGUI.errorAction, 
							UtilityGUI.titleAlert, JOptionPane.INFORMATION_MESSAGE);
				return;
			}
		}else if(e.getSource() == btnCancel){
			Main.jTabbedPane.remove(this);
		}
		
	}

}

